package server

import (
	"context"
	"etcd-desktop/server/repository"
	"fmt"
	"github.com/fsnotify/fsnotify"
	"github.com/spf13/viper"
	"go.uber.org/zap"
	"os"
)

var Environments Environment

// App struct
type App struct {
	ctx context.Context
}

// startup is called when the app starts. The context is saved
// so we can call the runtime methods
func (a *App) Startup(ctx context.Context) {
	// log  文件初始化
	configHome := repository.GetConfigHome() // mac: /Users/liuwei/Library/Preferences/EtcdDesktop
	dataHome := repository.GetDataHome()     // mac: /Users/liuwei/Library/EtcdDesktop
	fmt.Printf("configHome %s\n", configHome)
	fmt.Printf("dataHome %s\n", dataHome)
	InitLogger(dataHome)

	// env 配置文件初始化
	Environments := a.loadConfig()
	zap.S().Info("loading config", zap.String("config", Environments.Logging.File))

	// 持久层初始化
}

// Greet returns a greeting for the given name
func (a *App) Greet(name string) string {
	return fmt.Sprintf("Hello %s, It's show time!", name)
}

func (a *App) loadConfig() Environment {
	// 设置配置文件路径
	var env Environment
	config := "server/resources/application.yml"

	// 生产环境可以通过设置环境变量来改变配置文件路径
	if configEnv := os.Getenv("VIPER_CONFIG"); configEnv != "" {
		config = configEnv
	}
	zap.S().Info("loading config", zap.String("config", config))

	// 初始化 viper
	v := viper.New()
	v.AutomaticEnv()
	v.SetConfigFile(config)
	v.SetConfigType("yaml")
	if err := v.ReadInConfig(); err != nil {
		panic(fmt.Errorf("read config failed: %s \n", err))
	}

	// 监听配置文件
	v.WatchConfig()
	v.OnConfigChange(func(in fsnotify.Event) {
		fmt.Println("config fileDriver changed:", in.Name)
		// 重载配置,这里可以进行重启服务器,或者其他操作
		if err := v.Unmarshal(&env); err != nil {
			fmt.Println(err)
		}
	})

	// 将配置赋值给全局变量
	if err := v.Unmarshal(&env); err != nil {
		fmt.Println(err)
	}
	return env
}
